package com.eqdd.yiqidian.ui;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.ScanZXingActivityCustom;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.ErweimaBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.MyCodeUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.web.WebActivity;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;


import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import io.agora.rtc.video.EglBase14;

public class ScanZXingActivity extends BaseActivity {
    private static final String HAOYOU = "2";
    private static final String QUNZU = "1";
    private ScanZXingActivityCustom dataBinding;
    private String result;
    private boolean isLight = false;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_scan_zxing);
        initTopTitleBar(View.VISIBLE, "二维码识别");
    }

    @Override
    public void initData() {
        dataBinding.includeTitle.tvRight.setVisibility(View.VISIBLE);
        dataBinding.includeTitle.tvRight.setText("相册");
        dataBinding.includeTitle.tvRight.setOnClickListener((v) -> PicUtil.single(ScanZXingActivity.this)
        );

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    protected void onStart() {
        super.onStart();
        dataBinding.zxing.startCamera();
        dataBinding.zxing.showScanRect();
    }

    @Override
    protected void onDestroy() {
        dataBinding.zxing.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        dataBinding.zxing.stopCamera();
        super.onStop();
    }

    @Override
    public void setView() {
        dataBinding.zxing.setDelegate(new QRCodeView.Delegate() {
            @Override
            public void onScanQRCodeSuccess(String result) {
                ScanZXingActivity.this.result = result;
                dataBinding.zxing.startSpot();
                vibrate();
                addFriend();
            }

            @Override
            public void onScanQRCodeOpenCameraError() {
                dataBinding.zxing.startSpot();

            }
        });
        dataBinding.zxing.startSpot();
        RxView.clicks(dataBinding.tvLight)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(v -> {
                    if (isLight) {
                        dataBinding.zxing.closeFlashlight();
                        dataBinding.tvLight.setText("打开手电筒");
                        isLight = false;
                    } else {
                        dataBinding.zxing.openFlashlight();
                        dataBinding.tvLight.setText("关闭手电筒");
                        isLight = true;
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    private void addFriend() {
        try {
            ErweimaBean erweimaBean = GsonUtils.changeGsonToBean(result, ErweimaBean.class);
            if (erweimaBean != null) {
                showInputDialog(erweimaBean);
            } else {
                Bundle bundle = new Bundle();
                bundle.putString(Config.URL, result);
                bundle.putString(Config.TITLE, "扫描结果");
                startActivity(WebActivity.class, bundle);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Bundle bundle = new Bundle();
            bundle.putString(Config.URL, result);
            bundle.putString(Config.TITLE, "扫描结果");
            startActivity(WebActivity.class, bundle);
        }
    }

    private void showInputDialog(ErweimaBean erweimaBean) {
        String title = erweimaBean.getType().equals(HAOYOU) ? "添加" + erweimaBean.getName() + "为好友" : "加入" + erweimaBean.getName() + "群组";
        EditDialogFragment editDiglog = ChooseAlertView.getEditDiglog(title, "我是" + user.getPname(), "请输入验证信息", null, null, new EditDialogFragment.OnClickListener() {
            @Override
            public void onClick(List<String> contents) {
                if (erweimaBean.getType().equals(HAOYOU)) {
                    new HttpPresneter.Builder(HttpConfig.INVITE_FRIEND, BaseBean.class, ScanZXingActivity.this)
                            .Params("userid", user.getGuid())
                            .Params("friendid", erweimaBean.getUgid())
                            .Params("addcontent", contents.get(0))
                            .setOnHttpListener(new HttpPresneter.OnHttpListener<BaseBean>() {
                                @Override
                                public void onError(Throwable e) {
                                    System.out.println(e.toString());
                                }

                                @Override
                                public void onNext(BaseBean baseBean) {
                                    ToastUtil.showShort(baseBean.getMsg());
                                    System.out.println(baseBean.toString());
                                    finish();
                                }
                            })
                            .build()
                            .post();
                } else if (erweimaBean.getType().equals(QUNZU)) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_GROUP)
                            .params("userGuid", ";"+user.getGuid())
                            .params("Groupid", erweimaBean.getUgid())
                            .params("GroupName", erweimaBean.getName())
                            .execute(new DialogCallBack<HttpResult>(ScanZXingActivity.this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        finish();
                                    }
                                }
                            });
//                    new HttpPresneter.Builder(HttpConfig.ADD_GROUP, String.class, ScanZXingActivity.this)
//                            .Params("userGuid", user.getGuid())
//                            .Params("Groupid", erweimaBean.getUgid())
//                            .Params("GroupName", erweimaBean.getName())
//                            .setOnHttpListener(new HttpPresneter.OnHttpListener() {
//                                @Override
//                                public void onError(Throwable e) {
//                                }
//
//                                @Override
//                                public void onNext(Object o) {
//                                    if (((String) o).contains("200")) {
//                                        ToastUtil.showShort("你已成功加入该群组");
//                                    } else if (((String) o).contains("202")) {
//                                        ToastUtil.showShort("加入群组失败，请重试");
//                                    }
//                                    finish();
//                                }
//                            })
//                            .build()
//                            .post();
                }
            }
        });
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(editDiglog, "123");
        ft.commitAllowingStateLoss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    showLoading();
                    MyCodeUtil.analyzeBitmap(PictureSelector.obtainMultipleResult(data).get(0).getPath(), new MyCodeUtil.OnAnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(String content) {
                            result = content;
                            hideLoading();
                            addFriend();
                        }

                        @Override
                        public void onAnalyzeFailed() {

                            hideLoading();
                            ToastUtil.showShort("二维码解析失败");
                        }
                    });
                    break;
            }
        }
    }

}
